CODE 22. Minimum Depth of Binary Tree

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/09/19/2013-09-19-CODE 22 Minimum Depth of Binary Tree/

访问原文「CODE 22. Minimum Depth of Binary Tree

Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public int minDepth(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
if (null == root) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
int layer = 1;
int layerNumbers = 1;
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
layerNumbers--;
if (null == node.left && null == node.right) {
break;
}
if (null != node.left) {
queue.offer(node.left);
}
if (null != node.right) {
queue.offer(node.right);
}
if (layerNumbers == 0 && !queue.isEmpty()) {
layerNumbers = queue.size();
layer++;
}
}
return layer;
}
Jerky Lu wechat
欢迎加入微信公众号